new Vue({
    el: '#message',
    data: {
        messages: null,
        followers: null,
        fans: null,
        comments: null,
        likes: null,
        communicates: null,
        loginUser: null,
        responseUser: null,
        isChat: false
    },
    methods: {
        // 聊天
        chat: function (responseUserId) {

            // 自动聚焦
            setTimeout(function(){
                $("#message #input").focus()
            }, 100)
            this.isChat = true
            let that = this
            // 从关注列表和粉丝列表查找回复用户
            this.followers.forEach(ele => {
                if (ele.userId == responseUserId) {
                    that.responseUser = ele
                }
            })
            
            this.fans.forEach(ele => {
                if (ele.userId == responseUserId) {
                    that.responseUser = ele
                }
            })
            get("/getCommunicates/" + responseUserId, function (data) {
                that.communicates = data
            })
        }
    },
    created: function () {
        // 获取数据
        let that = this
        get("/loginUser", function (data) {
            that.loginUser = data
            if (data) {
                let userId = that.loginUser.userId
                get("/getCommentViewById/" + userId, function (data) {
                    that.comments = data
                })
                get("/getLikeViewById/" + userId, function (data) {
                    that.likes = data
                })

                get("/getFollowViewById/" + userId, function (data) {
                    that.followers = data
                })

                get("/getFanViewById/" + userId, function (data) {
                    that.fans = data
                })
            }
        })

        // enter键发送消息
        let websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket('ws://localhost:8080/webSocket');
        }
        else {
            alert('当前浏览器不支持websocket')
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            console.log("WebSocket连接发生错误");
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            console.log("WebSocket连接成功");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            if (that.communicates) {
                that.communicates.push(JSON.parse(event.data))
                // 修改头部导航栏的消息数量
                let message = $("#head #messageCount")
                message.html(parseInt(message.html()) + 1)
                message.show()
            }
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            console.log("WebSocket连接关闭");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }

        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }

        //发送消息
        function send(content) {
            // 先保存数据
            post("/saveCommunicate/" + that.responseUser.userId, {
                content: content
            })
            websocket.send(JSON.stringify({
                content: content,
                requestUserId: that.loginUser.userId,
                responseUserId: that.responseUser.userId,
                createTime: getTime()
            }));
        }
        $(function () {
            let input = $("#message #input")
            input.keydown(function (e) {
                if (e.which == 13) {
                    let message = input.val().trim()
                    if (message == "") {
                        swalError("发送失败", "发送的内容不能为空")
                        return
                    }
                    send(message)
                    input.val("")
                }
            })
        })
    }
})

exchangeDisplay("#message .leftNav .item", "#message .messageList >div")
function getTime() {
    var date = new Date();
    var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
    var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
    var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)

    var hours = date.getHours();          //小时 ,返回 Date 对象的小时 (0 ~ 23)
    var minutes = date.getMinutes();      //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
    var seconds = date.getSeconds();      //秒 ,返回 Date 对象的秒数 (0 ~ 59)   

    //修改月份格式
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }

    //修改日期格式
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }

    //修改小时格式
    if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
    }

    //修改分钟格式
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }

    //修改秒格式
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }

    //获取当前系统时间  格式(yyyy-mm-dd hh:mm:ss)
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}


